package main.parsers;

import java.util.HashMap;
import java.util.Map.Entry;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;

public class XmlPath 
{
	private static final XmlPath instance = new XmlPath ();
	private HashMap<String, XPathExpression> expressions;
	
	private XmlPath () {}
	
	public static XmlPath getInstance() 
	{
		return instance;
	}
	
	public void initialize(String filename) throws Exception
	{
		XPath xpath = XPathFactory.newInstance().newXPath();
		HashMap<String, String> queries = loadQueries(filename);
		expressions = new HashMap<String, XPathExpression>();
		for(Entry<String, String> entry: queries.entrySet())
		{
			expressions.put(entry.getKey(), xpath.compile(entry.getValue()));
		}
	}
	
	public NodeList execute(Document doc, String queryName) throws XPathExpressionException
	{
		
		/*NodeList nodes = (NodeList) expressions.get(queryName).evaluate(doc, XPathConstants.NODESET);
		String[] results = new String[nodes.getLength()];
		for (int i = 0; i < nodes.getLength(); i++) results[i] = nodes.item(i).getTextContent();
		return results;*/
		return (NodeList) expressions.get(queryName).evaluate(doc, XPathConstants.NODESET);
	}
	
	private HashMap<String, String> loadQueries(String conf) throws Exception
	{
		HashMap<String, String> queries = new HashMap<String, String>();
		Document config = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(conf);
		NodeList queryNodes = config.getDocumentElement().getElementsByTagName("query");
		for (int i = 0; i < queryNodes.getLength(); i++)
		{
			Element element = (Element)queryNodes.item(i);
			if (element.hasAttribute("name"))
			{
				Node xpath = element.getFirstChild();
				if (xpath instanceof Text)
				{
					queries.put(element.getAttribute("name"), xpath.getTextContent());
				}
			}
		}
		return queries;
	}
}
